package com.loong.controller;

import com.loong.pojo.User;
import com.loong.service.UserService;
import com.loong.service.impl.UserServiceImpl;
import com.loong.utils.Base64Utils;
import com.loong.utils.Constants;
import com.loong.utils.MD5Utils;
import com.loong.utils.RandomUtils;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.Cookie;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import org.apache.commons.beanutils.BeanUtils;

import java.lang.reflect.InvocationTargetException;
import java.util.Map;

/**
 * 用于用户模块的控制层
 */
@WebServlet("/user")
public class UserController extends BaseServlet{

    public String checkedUser(HttpServletRequest request, HttpServletResponse response){
//        1.获取用户名
        String username = request.getParameter("username");
        if(username == null){
            return Constants.HSA_USER;
        }
//        2.调用业务逻辑判断用户是否存在
        UserService userService = new UserServiceImpl();
        boolean flag = userService.checkedUser(username);
        if(flag){
            return Constants.HSA_USER;
        }
        return Constants.NOT_HSA_USER;
    }

    public String register(HttpServletRequest request, HttpServletResponse response){
//        1.获取用户名和密码
        Map<String, String[]> parameterMap = request.getParameterMap();
        User user = new User();
        try {
            BeanUtils.populate(user, parameterMap);
        } catch (IllegalAccessException | InvocationTargetException e) {
            throw new RuntimeException(e);
        }
        user.setStatus(Constants.USER_NOT_ACTIVE);//未激活
        user.setRole(Constants.ROLE_CUSTOMER);//普通用户
        user.setCode(RandomUtils.createActiveCode());
        //处理密码
        user.setPassword(MD5Utils.md5(user.getPassword()));
//        2.调用业务逻辑注册用户
        UserService userService = new UserServiceImpl();
        int row = userService.registerUser(user);
        if(row == 0){
            request.setAttribute("registerMsg", "注册失败");
            return Constants.FORWARD+"/register.jsp";
        }
        //3.返回注册成功页面
        //2.调用业务逻辑注册用户
        return Constants.FORWARD+"/registerSuccess.jsp";
    }

    /**
     * 用于激活用户
     * @param request
     * @param response
     * @return
     */
    public String active(HttpServletRequest  request, HttpServletResponse response){
        //1.获取激活码
        //已经转成base64
        String c = request.getParameter("c");
        //base64翻转
        String code = Base64Utils.decode(c);
        //2.调用业务逻辑激活用户
        UserService userService = new UserServiceImpl();
        int row = userService.activeUser(code);
        if(row == Constants.ACTIVE_FAIL){
            request.setAttribute("msg", "激活失败");
        } else if (row == Constants.ACTIVE_SUCCESS) {
            request.setAttribute("msg","激活成功，请登录");
        }else {
            request.setAttribute("msg","已经激活");
        }
        //3.返回激活成功页面
        return Constants.FORWARD+"/message.jsp";
    }
    /**
     * 前端提交账号密码和验证码
     * 对比验证码
     * 对比账号密码
     */
    public String login(HttpServletRequest request, HttpServletResponse response){
        //1.获取请求参数
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        String code = request.getParameter("code");//用户输入的验证码
        String auto = request.getParameter("auto");//是否自动登录
        //2.调用业务逻辑判断验证码是否正确
        HttpSession session = request.getSession();
        String codeStr = (String)session.getAttribute("code");
        if(code == null || !code.equalsIgnoreCase(codeStr)){
            request.setAttribute("msg", "验证码错误");
            return Constants.FORWARD+"/login.jsp";
        }
        //判断账号密码
        UserService userService = new UserServiceImpl();
        User user = userService.login(username, password);
        if(user == null){
            request.setAttribute("msg", "账号或密码错误");
            return Constants.FORWARD+"/login.jsp";
        }
        if (user.getStatus() == Constants.USER_NOT_ACTIVE) {
            request.setAttribute("msg", "账号未激活");
            return Constants.FORWARD+"/login.jsp";
        }
        //3.登录成功，保存用户信息到session
        session.setAttribute("loginUser", user);
        if(auto == null){
            Cookie cookie = new Cookie(Constants.AUTO_NAME, "");
            cookie.setPath("/");
            cookie.setMaxAge(0);
            response.addCookie(cookie);
        }else {
            String content = username + Constants.FLAG + password;
            content = Base64Utils.encode(content);
            Cookie cookie = new Cookie(Constants.AUTO_NAME, content);
            cookie.setPath("/");
            cookie.setMaxAge(14*24*60*60);
            response.addCookie(cookie);
        }
        //4.跳转到首页
        return Constants.REDIRECT+"/index.jsp";
    }

    /**
     * 退出登录 清空数据 跳转到登录页面
     * @param request
     * @param response
     * @return
     */
    public String logOut(HttpServletRequest request, HttpServletResponse response){
        //1.清除session
        HttpSession session = request.getSession();
        session.removeAttribute("loginUser");

        //2清除cookie
        Cookie cookie = new Cookie(Constants.AUTO_NAME, "");
        cookie.setPath("/");
        cookie.setMaxAge(0);
        response.addCookie(cookie);
        request.setAttribute("msg", "退出成功");
        return Constants.FORWARD+"/login.jsp";
    }
}
